package com.loongxun.playwithyou.ui.activity.user;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.Window;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.loongxun.playwithyou.ApiInterface;
import com.loongxun.playwithyou.R;
import com.loongxun.playwithyou.ali.ToAliActivity;
import com.loongxun.playwithyou.bean.Order;
import com.loongxun.playwithyou.bean.OrderMeg;
import com.loongxun.playwithyou.bean.SendRequest;
import com.loongxun.playwithyou.network.MyHttpClientRespenseHandler;
import com.loongxun.playwithyou.network.nHttpClient;
import com.loongxun.playwithyou.ui.adapter.UserOrderAdapter;
import com.loongxun.playwithyou.util.ToastView;
import com.loongxun.playwithyou.view.MyDialog;
import com.loongxun.playwithyou.view.pullableview.PullToRefreshLayout;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * 订单管理
 * Created by Administrator on 2017/8/10.
 */
public class UserOrderActivity extends Activity implements View.OnClickListener{

    private Context context;
    private SharedPreferences share;
    private SharedPreferences.Editor editor;
    private SendRequest send;
    private int orderState = 0,pageNo = 1;
    private String userId,orderNo;
    private boolean isPageNoMore = false;

    //标题
    private TextView tv_top_title;
    //代付款、待确认、待评价、已完成、取消管理
    private LinearLayout ll_user_order_1,ll_user_order_2,ll_user_order_3,ll_user_order_4,ll_user_order_5;

    private ListView listView;
    private PullToRefreshLayout ptrl;
    private boolean isFirstIn = true;
    private TextView loadstate_tv;
    private UserOrderAdapter mAdapter;
    private List<Order> orders = new ArrayList<>();

    public Handler messageHandler;
    private MyDialog mDialog;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_order);
        context = UserOrderActivity.this;
        share = context.getSharedPreferences("userInfo", 0);
        editor = share.edit();
        userId = share.getString("user_id", "");

        orderState = getIntent().getIntExtra("orderState",0);

        ptrl = ((PullToRefreshLayout) findViewById(R.id.refresh_view));
        loadstate_tv = (TextView) findViewById(R.id.loadstate_tv);
        ptrl.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(final PullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        pageNo = 1;
                        initData(pageNo);
                        // 千万别忘了告诉控件刷新完毕了哦！
                        pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 3000);
            }

            @Override
            public void onLoadMore(final PullToRefreshLayout pullToRefreshLayout) {
                // 下拉刷新操作
                new Handler() {
                    @Override
                    public void handleMessage(Message msg) {
                        if (isPageNoMore) {
                            pageNo = pageNo + 1;
                            initData(pageNo);
                        }else {
                            loadstate_tv.setText("已加载全部数据");
                        }
                        // 千万别忘了告诉控件刷新完毕了哦！
                        pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                    }
                }.sendEmptyMessageDelayed(0, 3000);

            }
        });
        listView = (ListView) findViewById(R.id.content_view);
        ptrl.autoRefresh();
        initView();
        changeTab(orderState);

        messageHandler = new Handler(){
            public void handleMessage(final Message msg) {
                Intent intent;
                final OrderMeg order = (OrderMeg) msg.obj;
                //0、取消订单,1、申请取消，2、评价
                switch (msg.what){
                    case 0:
                        mDialog = new MyDialog(context,"提示","是否取消订单？");
                        mDialog.show();
                        mDialog.positive.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mDialog.dismiss();
                                upOrder(order.getOrder_no(), "5");
                            }
                        });
                        mDialog.negative.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mDialog.dismiss();
                            }
                        });
                        break;
                    case 3:
                        mDialog = new MyDialog(context,"提示","是否确认陪练结束？");
                        mDialog.show();
                        mDialog.positive.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mDialog.dismiss();
                                upOrder(order.getOrder_no(), "2");
                            }
                        });
                        mDialog.negative.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                mDialog.dismiss();
                            }
                        });
                        break;
                    case 10:
                        orderNo = order.getOrder_no();
                        isToplay();
                        break;
                    case 11:
                        intent = new Intent(context, UserOrderInfoActivity.class);
                        intent.putExtra("orderNo",order.getOrder_no());
                        intent.putExtra("orderState",order.getOrderState());
                        intent.putExtra("start",order.getStart());
                        startActivityForResult(intent,11);
                        break;
                    default:
                        break;
                }
            }
        };
    }

    private void isToplay(){
        try {
            send = new SendRequest();
            send.orderNo = orderNo;
            //待支付订单再次支付的校验
            nHttpClient.getAll(ApiInterface.IS_TO_PLAY, send.toOrderMemberInfoJson().toString(), isToPlayHandler);
        }catch (Exception e){
            ToastView toast = new ToastView(context, "参数错误");
            toast.show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (data != null) {
            if (requestCode == 10) {
                if (data.getBooleanExtra("ALi",false)){
                    changeTab(1);
                    okOrder();
                }else {
                    failOrder();
                }
            }
            if (requestCode == 11) {
                changeTab(data.getIntExtra("orderState",0));
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //支付成功
    private void okOrder() {
        mDialog = new MyDialog(context,"支付成功","是否继续购物？");
        mDialog.show();
        mDialog.positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                //todo 去购物
            }
        });
        mDialog.negative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                orderState = 1;
                pageNo = 1;
                initData(pageNo);
            }
        });
    }

    //支付失败
    private void failOrder() {
        mDialog = new MyDialog(context,"支付失败","是否继续支付？");
        mDialog.show();
        mDialog.positive.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                orderState = 0;
                pageNo = 1;
                initData(pageNo);
            }
        });
        mDialog.negative.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
                orderState = 0;
                pageNo = 1;
                initData(pageNo);
            }
        });
    }

    //列表数据访问
    private void initData(int pageNo) {
        try {
            send = new SendRequest();
            send.userId = userId;
            send.orderState = orderState+"";
            send.pageNo = pageNo;
            //判断此会员是否为陪玩人员
            nHttpClient.getAll(ApiInterface.USER_ORDER_LIST, send.toUserOrderListJson().toString(), orderHandler);
        }catch (Exception e){
            ToastView toast = new ToastView(context, "参数错误");
            toast.show();
        }
    }

    //修改订单状态 orderState（取消订单传值=5，确认订单传值=2）
    private void upOrder(String orderNo,String state) {
        try {
            send = new SendRequest();
            send.orderState = state;
            send.orderNo = orderNo;
            //判断此会员是否为陪玩人员
            nHttpClient.getAll(ApiInterface.USER_UP_ORDER, send.toUpOrderJson().toString(), upOrderHandler);
        }catch (Exception e){
            ToastView toast = new ToastView(context, "参数错误");
            toast.show();
        }
    }

    private void initView() {
        findViewById(R.id.iv_back).setOnClickListener(this);
        tv_top_title = (TextView) findViewById(R.id.tv_top_title);
        tv_top_title.setText("订单管理");

        ll_user_order_1 = (LinearLayout) findViewById(R.id.ll_user_order_1);
        ll_user_order_2 = (LinearLayout) findViewById(R.id.ll_user_order_2);
        ll_user_order_3 = (LinearLayout) findViewById(R.id.ll_user_order_3);
        ll_user_order_4 = (LinearLayout) findViewById(R.id.ll_user_order_4);
        ll_user_order_5 = (LinearLayout) findViewById(R.id.ll_user_order_5);
        ll_user_order_1.setOnClickListener(this);
        ll_user_order_2.setOnClickListener(this);
        ll_user_order_3.setOnClickListener(this);
        ll_user_order_4.setOnClickListener(this);
        ll_user_order_5.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.iv_back:
                finish();
                break;
            case R.id.ll_user_order_1:
            case R.id.ll_user_order_2:
            case R.id.ll_user_order_3:
            case R.id.ll_user_order_4:
            case R.id.ll_user_order_5:
                changeTab(Integer.valueOf((String) view.getTag()));
                break;
            default:
                break;
        }
    }

    private void changeTab(int index) {
        orderState = index;
        pageNo = 1;
        initData(pageNo);
        ll_user_order_1.setSelected(index == 0);
        ll_user_order_2.setSelected(index == 1);
        ll_user_order_3.setSelected(index == 2);
        ll_user_order_4.setSelected(index == 3);
        ll_user_order_5.setSelected(index == 4);
    }

    public void setOrder() {
        if(mAdapter == null) {
            mAdapter = new UserOrderAdapter(context,orders,orderState);
            listView.setAdapter(mAdapter);
        }else {
            mAdapter.setType(orderState);
            mAdapter.setList(orders);
        }
        mAdapter.parentHandler = messageHandler;
    }

    private MyHttpClientRespenseHandler orderHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            JSONArray itemArray;
            if (succeed == 1) {
                try {
                    itemArray = json.getJSONObject("data").getJSONArray("orderList");
                    if (pageNo == 1) {
                        orders.clear();
                    }
                    for(int i = 0;i < itemArray.length();i++) {
                        JSONObject subItemObject = itemArray.getJSONObject(i);
                        Order order = new Order();
                        order.setHours_num(subItemObject.getInt("hours_num"));
                        order.setOrder_no(subItemObject.getString("order_no"));
                        order.setPlay_start_time(subItemObject.getString("play_start_time"));
                        order.setOrder_state(subItemObject.getInt("order_state"));
                        order.setIsExamine(subItemObject.getString("isExamine"));
                        String examineState = subItemObject.getString("examineState");
                        if ("null".equals(examineState) || "0".equals(examineState)) {
                            order.setExamine_state(0);
                        }else if ("1".equals(examineState)){
                            order.setExamine_state(1);
                        }else if ("2".equals(examineState)){
                            order.setExamine_state(2);
                        }
                        orders.add(order);
                    }
                    isPageNoMore = json.getJSONObject("data").getBoolean("isPageNoMore");
                    setOrder();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };

    private MyHttpClientRespenseHandler upOrderHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            if (succeed == 1) {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
                pageNo = 1;
                initData(pageNo);
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };

    private MyHttpClientRespenseHandler isToPlayHandler = new MyHttpClientRespenseHandler() {

        @Override
        public void success(JSONObject json) {
            Integer succeed = json.optJSONObject("status").optInt("succeed", 0);
            if (succeed == 1) {
                Intent intent = new Intent(context,ToAliActivity.class);
                intent.putExtra("orderNo", orderNo);
                intent.putExtra("subject", "");
                startActivityForResult(intent, 10);
            }else {
                String error_desc = json.optJSONObject("status").optString("error_desc");
                new ToastView(context, error_desc).show();
            }
        }

        @Override
        public void faile(String json) {
            new ToastView(context, json).show();
        }
    };
}
